import Vue from 'vue';
import Vuex from 'vuex';
import storage from '../utils/storage';
import { getUserInfo } from '@/api/common.js';
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    userInfo: storage.userInfo.get() || {},
    token: storage.token.get() || '',
    statusBarHeight: '25px',
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo || {};
      storage.userInfo.set(userInfo);
    },
    logout(state) {
      state.token = '';
      state.userInfo = {};
      storage.token.remove();
      storage.userInfo.remove();
    },
    setStatusBarHeight(state, height) {
      state.statusBarHeight = height;
    },
    setToken(state, token) {
      state.token = token;
      storage.token.set(state.token);
    },
  },
  actions: {
    // 获取系统用户信息
    async getUserInfo({ commit }) {
      try {
        const { data } = await getUserInfo();
        commit('setUserInfo', data);
        const pages = getCurrentPages();
        // 如果当前页是登录页
        if (pages[pages.length - 1].$page.fullPath.indexOf('pages/login/index') !== -1) {
          if (pages === 1) {
            uni.redirectTo({
              url: '/pages/index/index',
            });
          } else {
            uni.navigateBack();
          }
        }
      } catch (e) {
        uni.hideLoading();
        throw new Error(e);
      }
    },
  },
  getters: {
    userInfo: (state) => state.userInfo,
    isLogin: (state) => !!state.token,
    token: (state) => state.token,
    statusBarHeight: (state) => state.statusBarHeight,
  },
});

export default store;